﻿using System;
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;

namespace Silvery.Scene
{
    public class SceneLogic : SceneBase
    {
        public SceneLogic()
        {
            IsSelfLoopRun = true;
            
        }
        
        protected virtual void GotoHere(Point targetpoint)
        {
            if (Hero != null)
            {
                GotoHere(Hero, targetpoint);
            }
        }
        protected void GotoHere(ICanMove role, Point targetpoint)
        {
            bool isOver = false;
            Point newPoint = GlobaleMethod.ConvertToLogicPosition(role.Position);
            double vx = targetpoint.X - role.Position.X;
            double vy = targetpoint.Y - role.Position.Y;
            double length = Math.Sqrt(vx * vx + vy * vy);
            vx = (vx / length) * GlobleConfig.SceneGridSize.Width;
            vy = (vy / length) * GlobleConfig.SceneGridSize.Height;
            double sx = role.Position.X;
            double sy = role.Position.Y;
            double ex = targetpoint.X;
            double ey = targetpoint.Y;
            do
            {
                int x = (int)((sx + vx) / GlobleConfig.SceneGridSize.Width);
                int y = (int)((sy + vy) / GlobleConfig.SceneGridSize.Height);
                if (base.SceneGridData[y, x] != -16777216)
                {
                    sx += vx;
                    sy += vy;
                }
                else
                {
                    newPoint.X = sx ;
                    newPoint.Y = sy ;
                    break;
                }
                if (Math.Sqrt((ex - sx) * (ex - sx) + (ey - sy) * (ey - sy)) < GlobleConfig.SceneGridSize.Width)
                {
                    newPoint.X = sx ;
                    newPoint.Y = sy ;
                    isOver = true;
                    break;
                }
            }
            while (true);

            var moveQueue = new List<Point>();
            moveQueue.Insert(0, newPoint);
            moveQueue.Insert(0, (role.Position));
            if (!isOver)
            {
                var findpath = _AStarPathFinder.GetPath(
                    (int)(newPoint.X / GlobleConfig.SceneGridSize.Width),
                    (int)(newPoint.Y / GlobleConfig.SceneGridSize.Height),
                    (int)(targetpoint.X / GlobleConfig.SceneGridSize.Width),
                    (int)(targetpoint.Y / GlobleConfig.SceneGridSize.Height));
                moveQueue.AddRange(findpath);
            }
            role.GotoQueue = moveQueue;

        }

        
    }
}
